package com.wva.video.controller;

import com.wva.common.exception.BusinessException;
import com.wva.common.status.StatusEnum;
import com.wva.common.utils.R;
import com.wva.video.constant.UploadConst;
import com.wva.video.domain.dto.CheckChunksDTO;
import com.wva.video.domain.dto.SetChunkMd5DTO;
import com.wva.video.domain.vo.CheckChunksVO;
import com.wva.video.service.VideoResourceService;
import com.wva.video.service.VideoUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: hong
 * @Date: 2025/2/8 21:47:36
 */
@Api(tags = "视频上传相关接口")
@RequestMapping("/video/upload")
@RestController
public class UploadController {
    @Autowired
    VideoUploadService videoUploadService;
    @Autowired
    VideoResourceService videoResourceService;

    @ApiOperation("检查文件分片")
    @PostMapping("/checkChunks")
    R<Object> checkChunks(@Validated @RequestBody CheckChunksDTO checkChunksDTO) throws Exception {
        //检查文件大小
        int chunkNumber = checkChunksDTO.getChunkNumber();
        long chunkSize = checkChunksDTO.getChunkSize();
        if (chunkNumber*chunkSize > UploadConst.MAX_FILE_SIZE) {
            //超出最大上传文件大小
            throw new BusinessException("视频太大了，换一个吧");
        }

        //检查是否合并完毕
        if (videoUploadService.isChunksMerged(checkChunksDTO.getFileMd5())) {
            return new R<>(StatusEnum.VIDEO_MERGED);
        }

        //断点续传：返回此文件分块上传状态
        CheckChunksVO checkChunksVO = videoUploadService.checkChunks(checkChunksDTO);
        return R.ok(checkChunksVO);
    }

    @ApiOperation("设置分片md5")
    @PostMapping("/setChunkMd5")
    R<Object> setChunkMd5(@Validated @RequestBody SetChunkMd5DTO setChunkMd5DTO) {
        videoUploadService.setChunkMd5(setChunkMd5DTO);
        return R.ok();
    }

    /**
     * 此接口仅是提交合并任务，具体结果需要后续前端轮询查询是否合并成功
     * @param fileMd5
     * @return
     * @throws Exception
     */
    @ApiOperation("请求合并分块")
    @GetMapping("/mergeChunks")
    R<Object> mergeChunks(@RequestParam String fileMd5) throws Exception {
        videoUploadService.mergeChunks(fileMd5);
        return R.ok();
    }
}
